package com.ysstech.schedule.controller;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.schedule.entity.ScheduleJob;
import com.ysstech.schedule.service.ScheduleJobService;
import com.ysstech.schedule.utils.ScheduleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lishuangliang
 * @since 2020-09-21
 */
@Slf4j
@Api(tags = "定时任务管理api")
@Controller
@RequestMapping("/scheduleJob")
public class ScheduleJobController extends BaseController {

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private ScheduleJobService scheduleJobService;

    @YssPermissions(value = {"schedule:job"})
    @ApiOperation(value = "跳转到定时任务管理页面")
    @YssLog(module = "定时任务管理中心", remark = "跳转到定时任务管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "schedule/job";
    }


    @YssPermissions(value = {"schedule:job"})
    @ApiOperation(value = "获取定时任务管理页面任务模块的值")
    @YssLog(module = "定时任务管理中心", remark = "获取定时任务管理页面任务模块的值")
    @RequestMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {

        return ResultGenerator.getSuccessResult("获取页面初始化信息成功");
    }


    @YssPermissions(value = {"schedule:job"})
    @ApiOperation(value = "获取所有定时任务信息")
    @YssLog(module = "定时任务管理中心", remark = "获取所有定时任务信息")
    @RequestMapping(value = "/listScheduleJob")
    @ResponseBody
    public RestResult listScheduleJob(ScheduleJob scheduleJob, String page, String rows) throws Exception {
        return ResultGenerator.getSuccessResult("获取所有定时任务类别信息成功", scheduleJobService.listScheduleJob(scheduleJob, this.getPage(page, rows)));
    }

    @YssPermissions(value = {"schedule:job:add"})
    @ApiOperation(value = "新增定时任务")
    @YssLog(module = "定时任务管理中心", remark = "新增定时任务")
    @RequestMapping(value = "/addScheduleJob")
    @ResponseBody
    public RestResult addScheduleJob(ScheduleJob scheduleJob) throws Exception {
        scheduleJob.setId(DateUtil.generateUUID());
        scheduleJob.setAddTime(LocalDateTime.now());
        scheduleJobService.save(scheduleJob);
        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
        return ResultGenerator.getSuccessResult("新增定时任务成功");
    }

    @YssPermissions(value = {"schedule:job:edit"})
    @ApiOperation(value = "修改定时任务")
    @YssLog(module = "定时任务管理中心", remark = "修改定时任务")
    @RequestMapping(value = "/editScheduleJob")
    @ResponseBody
    public RestResult editScheduleJob(ScheduleJob scheduleJob) throws Exception {
        scheduleJob.setAddTime(LocalDateTime.now());
        scheduleJobService.updateById(scheduleJob);
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        return ResultGenerator.getSuccessResult("修改定时任务成功");
    }

    @YssPermissions(value = {"schedule:job:del"})
    @ApiOperation(value = "删除定时任务")
    @YssLog(module = "定时任务管理中心", remark = "删除定时任务")
    @RequestMapping(value = "/deleteScheduleJob")
    @ResponseBody
    public RestResult deleteScheduleJob(String arrJobId) throws Exception {
        if (StringUtils.isBlank(arrJobId)) {
            throw new BusinessException("获取定时任务信息失败，请稍后重试！");
        }
        List<String> JobIds = JSONArray.parseArray(arrJobId, String.class);
        scheduleJobService.removeByIds(JobIds);
        ScheduleUtils.deleteScheduleJobs(scheduler, JobIds);
        return ResultGenerator.getSuccessResult("删除定时任务成功");
    }

    @YssPermissions(value = {"schedule:job:run"})
    @ApiOperation(value = "立即执行定时任务")
    @YssLog(module = "定时任务管理中心", remark = "立即执行定时任务")
    @RequestMapping(value = "/runScheduleJob")
    @ResponseBody
    public RestResult runScheduleJob(ScheduleJob scheduleJob) throws Exception {
        ScheduleUtils.run(scheduler, scheduleJob);
        return ResultGenerator.getSuccessResult("立即执行定时任务成功");
    }

    @YssPermissions(value = {"schedule:job:pause"})
    @ApiOperation(value = "暂停定时任务")
    @YssLog(module = "定时任务管理中心", remark = "暂停定时任务")
    @RequestMapping(value = "/pauseJob")
    @ResponseBody
    public RestResult pauseJob(String arrJobId) throws Exception {
        if (StringUtils.isBlank(arrJobId)) {
            throw new BusinessException("获取定时任务信息失败，请稍后重试！");
        }
        List<String> JobIds = JSONArray.parseArray(arrJobId, String.class);
        List<ScheduleJob> list = new ArrayList<>();
        for (String jobId : JobIds) {
            ScheduleJob scheduleJob = new ScheduleJob();
            scheduleJob.setAddTime(LocalDateTime.now());
            scheduleJob.setId(jobId);
            scheduleJob.setStatus(2);
            list.add(scheduleJob);
        }
        if (!CollectionUtils.isEmpty(list)) {
            scheduleJobService.updateBatchById(list);
            ScheduleUtils.pauseJobs(scheduler, JobIds);
        }
        return ResultGenerator.getSuccessResult("暂停定时任务成功");
    }

    @YssPermissions(value = {"schedule:job:resume"})
    @ApiOperation(value = "恢复定时任务")
    @YssLog(module = "定时任务管理中心", remark = "恢复定时任务")
    @RequestMapping(value = "/resumeScheduleJob")
    @ResponseBody
    public RestResult resumeScheduleJob(String arrJobId) throws Exception {
        if (StringUtils.isBlank(arrJobId)) {
            throw new BusinessException("获取定时任务信息失败，请稍后重试！");
        }
        List<String> JobIds = JSONArray.parseArray(arrJobId, String.class);
        List<ScheduleJob> list = new ArrayList<>();
        for (String jobId : JobIds) {
            ScheduleJob scheduleJob = new ScheduleJob();
            scheduleJob.setAddTime(LocalDateTime.now());
            scheduleJob.setId(jobId);
            scheduleJob.setStatus(1);
            list.add(scheduleJob);
        }
        if (!CollectionUtils.isEmpty(list)) {
            scheduleJobService.updateBatchById(list);
            ScheduleUtils.resumeJobs(scheduler, JobIds);
        }
        return ResultGenerator.getSuccessResult("恢复定时任务成功");
    }

}
